#!/usr/bin/env python
# encoding: utf-8
"""
deploy.py

Created by rikugun on 2010-08-25.
Copyright (c) 2010 TYDIC. All rights reserved.

部署工具集合
"""

import sys
import os
import ftplib
from multiprocessing import Process,Queue
from ConfigParser import RawConfigParser
from copy import copy
from tydic_utils.base import get_conf_path

def deploy_web():
	"""传输web文件"""
	conf = RawConfigParser()
	conf.read(get_conf_path())
	opts,task_queue = parser_args()
	os.chdir(conf.get('Deploy FTP','work_dir'))
	
	def worker(server,conf,task_queue):
		with Transfer(server,conf,task_queue) as ftp:
			ftp.trans_file()
	
	for server in conf.get('Deploy FTP','server_list').split(','):
		task_queue_clone = copy(task_queue)
		try:
			proccess_base = conf.getint(server,'proccess_base')
		except :
			proccess_base = conf.getint('Deploy FTP','proccess_base')
		
		for x in range(task_queue_clone.qsize()/proccess_base))
			Process(target=worker,args=(server,conf,task_queue_clone)).start()

class Transfer(object):
	"""文件传输类"""
	def __init__(self,server,conf,task_queue):
		super(Tranfser, self).__init__()
		self.ins = ftplib.FTP(host=conf.get(server,'host'))
		self.conf = conf
		self.task = task_queue
	def __enter__(self):
		self.ins.login(user=conf['user'],passwd=conf['passwd'],acct=conf['acct'])
	def __exit__(self):
		self.ins.close()
	def trans_file(self):
		while True:
			filename = self.task.get()
			print u'传输 %s' % filename
			self.ins.storlines('STOR %s ' % filename,filename)
			self.task.task_done()
			

def parser_args():
	"""
	获取参数
	"""
	opt = optparse.OptionParser("tydic_deploy_web  [-L listfile] filepath [other files]")
	opt.add_option("-L","--listfile",help=u"提交的文件列表")
	opt.add_option("-q","--quite",action="store_true",help=u"安静模式,所有提示都选择Y")
	opt.add_option("-D","--delete",action="store_true",help=u"删除模式")
	opt.add_option("-d","--debug",action="store_true",help=u"调试模式")
	opts,files = opt.parse_args()
	if len(files) == 0 and opts.listfile is None:
		print u'请输入要提交文件,或者文件列表'
		print opt.print_usage()
		print __doc__
		exit(2)
	if not files and self.opts.listfile:
		files = [line.strip() for line in open(opts.listfile,'r').readlines() if not line.startswith('#')]
	task_queue = Queue.Queue()
	for it in files:
		if os.path.exists(it):
			task_queue.put(it)
	return opts,task_queue

def main():
	pass


if __name__ == '__main__':
	main()

